package com.tiger.cloud.service.crm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tiger.cloud.common.exception.ServiceException;
import com.tiger.cloud.common.mybatis.MybatisTigerDao;
import com.tiger.cloud.common.mybatis.TigerBaseService;
import com.tiger.cloud.common.view.SpringUtils;
import com.tiger.cloud.dao.crm.PeersDao;
import com.tiger.cloud.dao.crm.RecommandListDao;
import com.tiger.cloud.dao.crm.UserDao;
import com.tiger.cloud.dao.crm.UserInfoDao;
import com.tiger.cloud.enums.CommucationCustomerType;
import com.tiger.cloud.enums.DeleteEnum;
import com.tiger.cloud.enums.PointCodeEnum;
import com.tiger.cloud.enums.RecommandListAcceptStatus;
import com.tiger.cloud.enums.RecommandListStatus;
import com.tiger.cloud.enums.ResourceTypeEnum;
import com.tiger.cloud.form.CommucationMessage;
import com.tiger.cloud.model.crm.Commucation;
import com.tiger.cloud.model.crm.Peers;
import com.tiger.cloud.model.crm.RecommandList;
import com.tiger.cloud.model.crm.SystemCommucation;
import com.tiger.cloud.model.crm.User;
import com.tiger.cloud.model.crm.UserInfo;
import com.tiger.cloud.model.share.PointCodeMessage;
import com.tiger.cloud.util.ErrorCode;
import com.tiger.cloud.util.StringUtils;

/**
 * 好友推荐、申请
 */
@Service("recommandListService")
public class RecommandListService extends TigerBaseService<RecommandList> implements IRecommandListService {

	@Autowired
	private RecommandListDao recommandListDao;
	@Autowired
	private IPeersService peersService;
	@Autowired
	private ICommucationService commucationService;
	@Autowired
	private PeersDao peersDao;
	@Autowired
	private IUserService userService;
	@Autowired
	private UserDao userDao;

	@Override
	public MybatisTigerDao<RecommandList> getEntityDao() {
		return recommandListDao;
	}
	
	public List<User> notAddCount(){
		return recommandListDao.notAddCount();
	}
	
	public List<User> notAcceptCount(){
		return recommandListDao.notAcceptCount();
	}
	
	public long findAreaRecommandCount(Map<String, Object> params){
		return recommandListDao.findAreaRecommandCount(params);
	}
	
	public long findAreaRecommandCount(Long provinceId,Long cityId,Long districtId,Long userId,Integer limitStart,Integer limitEnd){
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("provinceId",provinceId);
		params.put("districtId",districtId);
		params.put("cityId", cityId);
		params.put("limitStart", limitStart);
		params.put("limitEnd", limitEnd);
		return recommandListDao.findAreaRecommandCount(params);
	}

	public List<RecommandList> findAreaRecommandList(Integer typeId,Long provinceId,Long cityId,Long districtId,Long userId,Integer limitStart,Integer limitEnd){
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("provinceId",provinceId);
		params.put("districtId",districtId);
		params.put("cityId", cityId);
		params.put("limitStart", limitStart);
		params.put("limitEnd", limitEnd);
		params.put("typeId", typeId);
		return recommandListDao.findAreaRecommandList(params);
	}
	
	public boolean updateByUserId(RecommandList recommandList) {
		if (recommandListDao.updateByUserId(recommandList) > 0) {
			return true;
		} else {
			throw new ServiceException(ErrorCode.UPDATE_RECOMMAND_LIST_ERROR);
		}
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean acceptRequest(RecommandList findRecommandList, Long userId) {
		updateByUserId(new RecommandList() {
			private static final long serialVersionUID = 1L;
			{
				setAcceptStatus(RecommandListAcceptStatus.ACCEPTED);
				setStatus(RecommandListStatus.CREATED);
				setIsDelete(DeleteEnum.NOMAIL);
				setAcceptIsDelete(DeleteEnum.NOMAIL);
				setAcceptDate(new Date());
				setUserId(findRecommandList.getUserId());
				setRecommandId(findRecommandList.getRecommandId());
			}
		});
		List<Peers> aList = new ArrayList<Peers>();

		Peers peers = new Peers();
		peers.setIsDelete(DeleteEnum.NOMAIL);
		peers.setResourceType(findRecommandList.getRecommandWay());
		peers.setPeerId(findRecommandList.getRecommandId());
		peers.setUserId(findRecommandList.getUserId());
		peers.setLevel("T3");
		aList.add(peers);

		peers = new Peers();
		peers.setIsDelete(DeleteEnum.NOMAIL);
		peers.setResourceType(findRecommandList.getRecommandWay());
		peers.setPeerId(findRecommandList.getUserId());
		peers.setUserId(findRecommandList.getRecommandId());
		peers.setLevel("T3");
		aList.add(peers);
		
		Peers findPeers = new Peers();
		findPeers.setPeerId(findRecommandList.getUserId());
		findPeers.setUserId(findRecommandList.getRecommandId());
		
		if(peersDao.countByUserId(findPeers)==0){
			peersService.insertBatch(aList);
		}
		Peers findPeers2 = new Peers();
		findPeers2.setIsDelete(DeleteEnum.NOMAIL);
		findPeers2.setUserId(findRecommandList.getUserId());
		findPeers2.setPeerId(findRecommandList.getRecommandId());
		peersService.updateByUserId(findPeers2);
		
		// 2017-9-10，您添加XXX到您的人脉圈
		List<UserInfo> userInfos = SpringUtils.getBean(UserInfoDao.class)
				.findInUserId(Arrays.asList(findRecommandList.getRecommandId(), findRecommandList.getUserId()));
		List<SystemCommucation> systemCommucations = new ArrayList<SystemCommucation>();
		userInfos.forEach(userInfo -> {
			SystemCommucation systemCommucation = new SystemCommucation();
			systemCommucation.setUserId(findRecommandList.getUserId().longValue() == userInfo.getUserId().longValue() ? findRecommandList.getUserId()
					: findRecommandList.getRecommandId());
			systemCommucation.setCustomerId(findRecommandList.getRecommandId().longValue() == userInfo.getUserId().longValue()
					? findRecommandList.getUserId() : findRecommandList.getRecommandId());
			systemCommucation.setCustomerType(CommucationCustomerType.PEERS);
			userInfos.forEach(userInfo2 -> {
				if (userInfo2.getUserId().longValue() != userInfo.getUserId().longValue()) {
					systemCommucation.setContent(CommucationMessage.getMsg(CommucationMessage.ADD_PEER_MESSAGE, userInfo2.getUserName()));
				}
			});
			systemCommucations.add(systemCommucation);
		});
		if (SpringUtils.getBean(ICommucationService.class).insertSystemCommucation(systemCommucations)) {
			
			Commucation commucation = new Commucation();
			commucation.setUserId(findRecommandList.getUserId());
			commucation.setCustomerId(findRecommandList.getRecommandId());
			commucation.setIsDelete(DeleteEnum.NOMAIL);
			commucation.setCustomerType(CommucationCustomerType.PEERS);
			commucationService.updateByUserId(commucation);
			updateAccount(findRecommandList);
		}
		return true;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean recommandUser(RecommandList recommandList, Long userId) {
		RecommandList findRecommandList = new RecommandList();
		findRecommandList.setUserId(recommandList.getUserId());
		findRecommandList.setRecommandId(recommandList.getRecommandId());
		RecommandList recommandListObj = recommandListDao.getRecommand(findRecommandList);
		String userName = "";
		if(!StringUtils.isEmpty(recommandList.getRecommandName())){
			userName = recommandList.getRecommandName();
		}
		if (recommandListObj != null) {
			// 已经存在,但是被一方删除过
			if (recommandListObj.getAcceptIsDelete() == DeleteEnum.DELETE || recommandListObj.getIsDelete() == DeleteEnum.DELETE) {
				//不是删除方请求添加
				if(recommandListObj.getAcceptIsDelete() == DeleteEnum.NOMAIL && recommandListObj.getRecommandId().longValue() ==userId.longValue()
						||recommandListObj.getIsDelete() == DeleteEnum.NOMAIL && recommandListObj.getUserId().longValue() ==userId.longValue()){
					return true;
				}
				RecommandList updateRecommandList = new RecommandList();
				updateRecommandList.setUserId(recommandList.getUserId());
				updateRecommandList.setRemark(recommandList.getRemark());
				updateRecommandList.setRecommandId(recommandList.getRecommandId());
				updateRecommandList.setAcceptIsDelete(DeleteEnum.NOMAIL);
				updateRecommandList.setIsDelete(DeleteEnum.NOMAIL);
				if (updateByUserId(updateRecommandList)) {
					Peers peers = new Peers();
					peers.setIsDelete(DeleteEnum.NOMAIL);
					peers.setUserId(recommandList.getUserId());
					peers.setPeerId(recommandList.getRecommandId());
					if (peersService.updateByUserId(peers) ) {
						Commucation commucation = new Commucation();
						commucation.setUserId(recommandList.getUserId());
						commucation.setCustomerId(recommandList.getRecommandId());
						commucation.setIsDelete(DeleteEnum.NOMAIL);
						commucation.setCustomerType(CommucationCustomerType.PEERS);
						commucationService.updateByUserId(commucation);
						return true;
					}
				}
			} else {
				if (recommandListObj.getUserId().longValue() == userId.longValue()) {// 当前用户主动添加
					if(recommandListObj.getStatus()==RecommandListStatus.CREATED){
						return true;
					}
					RecommandList updateRecommandList = new RecommandList();
					updateRecommandList.setUserId(recommandList.getUserId());
					updateRecommandList.setRecommandId(recommandList.getRecommandId());
					updateRecommandList.setStatus(RecommandListStatus.PEND_VERIF);
					updateRecommandList.setAcceptIsDelete(DeleteEnum.NOMAIL);
					updateRecommandList.setIsDelete(DeleteEnum.NOMAIL);
					updateRecommandList.setRemark(recommandList.getRemark());
					if(updateByUserId(updateRecommandList)){
						User user = userDao.findOneByUserId(recommandList.getRecommandId());
//						userService.sendJpushMessage(user.getJpushCode());
//                      userService.sendPushForAlert(user.getJpushCode(),userName);
						return true;
					}
				} else {
					if(recommandListObj.getAcceptStatus()==RecommandListAcceptStatus.ACCEPTED){
						return true;
					}
					if (recommandListObj.getStatus() == RecommandListStatus.WAIT_CREATE) {//待添加
						RecommandList updateRecommandList = new RecommandList();
						updateRecommandList.setId(recommandListObj.getId());
						updateRecommandList.setUserId(recommandList.getUserId());
						updateRecommandList.setRecommandId(recommandList.getRecommandId());
						updateRecommandList.setStatus(RecommandListStatus.PEND_VERIF);
						updateRecommandList.setAcceptIsDelete(DeleteEnum.NOMAIL);
						updateRecommandList.setIsDelete(DeleteEnum.NOMAIL);
						updateRecommandList.setRemark(recommandList.getRemark());
						if(recommandListDao.update2(updateRecommandList)>0){
							User user = userDao.findOneByUserId(recommandList.getUserId());
							userService.sendJpushMessage(user.getJpushCode());
							userService.sendPushForAlert(user.getJpushCode(),userName);
							return true;
						}
					}else{//已经匹配上,接收方添加
						if(acceptRequest(findRecommandList, userId)){
							updateAccount(recommandListObj);
							User user = userDao.findOneByUserId(recommandList.getUserId());
							userService.sendJpushMessage(user.getJpushCode());
							userService.sendPushForAlert(user.getJpushCode(),userName);
							return true;
						}
					}
				}
			}
		} else {
			if(recommandListDao.insert(recommandList) > 0){
				User user = userDao.findOneByUserId(recommandList.getRecommandId());
				userService.sendJpushMessage(user.getJpushCode());
				userService.sendPushForAlert(user.getJpushCode(),userName);
			}
			return true;
		}
		throw new ServiceException(ErrorCode.INSERT_RECOMMAND_LIST_ERROR);
	}

	private void updateAccount(RecommandList recommandList){
		try {
			if (recommandList.getRecommandWay() == ResourceTypeEnum.CRM_MATCH) {// 手机搜索添加
				if (SpringUtils.getBean(IUserConsumeService.class).insertRecord(PointCodeEnum.SEARCH_ADD_USER.getCode(), recommandList.getUserId(), PointCodeMessage.getMsg(PointCodeMessage.SEARCH_ADD_USER, CommonPointRule.getPoint(PointCodeEnum.SEARCH_ADD_USER.getCode()))) != null) {
					if (SpringUtils.getBean(IUserConsumeService.class).insertRecord(PointCodeEnum.ACCEPT_SEARCH_ADD_USER.getCode(), recommandList.getRecommandId(), PointCodeMessage.getMsg(PointCodeMessage.ACCEPT_SEARCH_ADD_USER, CommonPointRule.getPoint(PointCodeEnum.ACCEPT_SEARCH_ADD_USER.getCode()))) != null) {
					}

				}
			} else if (recommandList.getRecommandWay() == ResourceTypeEnum.QR_CODE) {// 扫码添加
				if (SpringUtils.getBean(IUserConsumeService.class).insertRecord(PointCodeEnum.SHARE_CODE_ADD_USER_ACTIVE.getCode(), recommandList.getUserId(), PointCodeMessage.getMsg(PointCodeMessage.SHARE_CODE_ADD_USER_ACTIVE, CommonPointRule.getPoint(PointCodeEnum.SHARE_CODE_ADD_USER_ACTIVE.getCode()))) != null) {
					if (SpringUtils.getBean(IUserConsumeService.class).insertRecord(PointCodeEnum.SHARE_CODE_ADD_USER_PASSIVE.getCode(), recommandList.getRecommandId(), PointCodeMessage.getMsg(PointCodeMessage.SHARE_CODE_ADD_USER_PASSIVE, CommonPointRule.getPoint(PointCodeEnum.SHARE_CODE_ADD_USER_PASSIVE.getCode()))) != null) {
					}
				}
			}else if(recommandList.getRecommandWay() == ResourceTypeEnum.ADDRESSBOOK){
				if (SpringUtils.getBean(IUserConsumeService.class).insertRecord(PointCodeEnum.MAIL_LIST_ADD_USER.getCode(), recommandList.getUserId(), PointCodeMessage.getMsg(PointCodeMessage.MAIL_LIST_ADD_USER, CommonPointRule.getPoint(PointCodeEnum.MAIL_LIST_ADD_USER.getCode()))) != null) {
					if (SpringUtils.getBean(IUserConsumeService.class).insertRecord(PointCodeEnum.ACCEPT_MAIL_LIST_ADD_USER.getCode(), recommandList.getRecommandId(), PointCodeMessage.getMsg(PointCodeMessage.ACCEPT_MAIL_LIST_ADD_USER, CommonPointRule.getPoint(PointCodeEnum.ACCEPT_MAIL_LIST_ADD_USER.getCode()))) != null) {
					}
				}

			}else if(recommandList.getRecommandWay() == ResourceTypeEnum.PEER_CIRCLE){
				if (SpringUtils.getBean(IUserConsumeService.class).insertRecord(PointCodeEnum.ADD_PEER_CIRCLE.getCode(), recommandList.getUserId(), PointCodeMessage.getMsg(PointCodeMessage.PEER_CIRCLE_ADD_USER, CommonPointRule.getPoint(PointCodeEnum.ADD_PEER_CIRCLE.getCode()))) != null) {
					if (SpringUtils.getBean(IUserConsumeService.class).insertRecord(PointCodeEnum.ACCEPT_PEER_CIRCLE.getCode(), recommandList.getRecommandId(), PointCodeMessage.getMsg(PointCodeMessage.ACCEPT_PEER_CIRCLE_ADD_USER, CommonPointRule.getPoint(PointCodeEnum.ACCEPT_PEER_CIRCLE.getCode()))) != null) {
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(ErrorCode.UPDATE_CUSTOMER_POINT_ERROR);
		}
	}

	@Override
	public RecommandList getRecommand(RecommandList recommandList) {
		return recommandListDao.getRecommand(recommandList);
	}

	@Override
	public Long findNotAccept(RecommandList recommandList) {
		try {
			return recommandListDao.findNotAccept(recommandList);
		} catch (Exception e){
			System.out.print("查询用户未接受数量出错："+e.getMessage().toLowerCase());
          return 0L;
		}
	}

}